
import time

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

from app.configs.config import (TIME_SLEEP, chromedriver_headless,
                                chromedriver_path)


def get_driver():
    """
        获取 webdriver
    """    
    service = Service(chromedriver_path)
    
    option = webdriver.ChromeOptions()  # 实例化一个浏览器对象
    
    if chromedriver_headless:
        option.add_argument('--headless')  # 添加参数，option可以是headless，--headless，-headless

    option.add_argument('--no-sandbox')  # fix:DevToolsActivePort file doesn't exist
    # option.add_argument('--disable-gpu')  # fix:DevToolsActivePort file doesn't exist
    option.add_argument('--disable-dev-shm-usage')  # fix:DevToolsActivePort file doesn't exist
    option.add_argument('--remote-debugging-port=9222')  # fix:DevToolsActivePort file doesn't

    driver = webdriver.Chrome(options=option, service=service)
    return driver  

driver = get_driver()



def click_element(driver, xpath, time_sleep=TIME_SLEEP):
    """
        点击元素
    """
    # 缓冲
    time.sleep(time_sleep)

    # 查找元素
    elment_div = driver.find_element(by=By.XPATH, value=xpath)

    # 创建动作对象
    action = ActionChains(driver) 
    action.click(elment_div) 

    # 执行动作
    action.perform()
    

def input_element(driver, xpath, input_text, time_sleep=TIME_SLEEP):
    """
        输入信息
    """
    # 缓冲
    time.sleep(time_sleep)

    driver.find_element(by=By.XPATH, value=xpath).send_keys(input_text)


def get_element_value(driver, xpath, attr_name, time_sleep=TIME_SLEEP):
    """
        获取元素的属性值
    """
    # 缓冲
    time.sleep(time_sleep)
    
    geetest_tip_img = driver.find_element(by=By.XPATH, value=xpath)
    return geetest_tip_img.get_attribute(attr_name)

def save_image(driver, xpath,save_path, time_sleep=TIME_SLEEP):
    """
        获取元素的属性值
    """
    # 缓冲
    time.sleep(time_sleep)
    
    image_element = driver.find_element(by=By.XPATH, value=xpath)
    
    with open(save_path, 'wb') as f:
        f.write(image_element.screenshot_as_png)


